package com.zsc.newbuds.service.impl;

import com.zsc.newbuds.entity.Shop;
import com.zsc.newbuds.mapper.ShopMapper;
import com.zsc.newbuds.service.ShopService;
import com.zsc.newbuds.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ShopServiceImpl implements ShopService {
    @Autowired
    ShopMapper shopMapper;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public List<Shop> getGoodsList() {
        List<Shop> goodsList = new ArrayList<Shop>();
        String key = "list:shopList";
        if(redisUtil.hasKey(key)){
            System.out.println("从redis中获取goodsList");
            Map<Object, Object> map = redisUtil.hmget(key);
            for(Map.Entry<Object, Object> shop:map.entrySet()){
                Shop goods = (Shop) shop.getValue();
                goodsList.add(goods);
            }
        }else {
            System.out.println("从数据库中获取goodsList");
            Map< String,Object> map = new HashMap<>();
            goodsList = shopMapper.getGoodsList();
            for (Shop shop : goodsList){
                map.put(shop.getGoodsId().toString(),shop);
            }
            redisUtil.hmset(key,map);
        }
        Collections.sort(goodsList);
        return goodsList;
    }

    @Override
    public void addGoods(Shop shop) {
        String shopKey = "list:shopList";
        shopMapper.addGoods(shop);
        if(redisUtil.hasKey(shopKey)){
            redisUtil.hset(shopKey,shop.getGoodsId().toString(),shopMapper.getGoodsById(shop.getGoodsId()));
        }
    }

    @Override
    public List<Shop> getGoodsMainList(Integer page,Integer limit) {
        List<Shop> goodsMainList;
        System.out.println("从数据库中获取goodsList");
        goodsMainList = shopMapper.getGoodsMainList(page,limit);
        System.out.println(goodsMainList);
        Collections.sort(goodsMainList);
        return goodsMainList;
    }

    @Async
    @Override
    public void goodsExchange(Integer id) {
        String key = "list:shopList";
        Shop shop = (Shop)redisUtil.hget(key,id.toString());
        System.out.println(shop);
        shop.setGoodsCount(shop.getGoodsCount()-1);
        redisUtil.hset(key,id.toString(),shop);
        shopMapper.updateShopCount(id,shop.getGoodsCount(),0);

    }

    @Override
    public void addGoodsCount(Integer[] goodsId,int count) {
        String key = "list:shopList";
        for (Integer id : goodsId){
            Shop shop = (Shop)redisUtil.hget(key,id.toString());
            int newCount = shop.getGoodsCount() + count;
            System.out.println("增加后的数量"+newCount);
            shop.setGoodsCount(newCount);
            redisUtil.hset(key,id.toString(),shop);
            shopMapper.updateCount(id,newCount);
        }
    }
}
